/* eslint-disable @typescript-eslint/indent */
/* eslint-disable indent */
/** eslint-disable */
import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import { Form, Button, Input, Radio, TreeSelect, Spin } from 'antd';
// import cookie from 'js-cookie';
import { QuickForm } from 'vv-frontend-components';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import useTreeSelectData from '@/hooks/useTreeSelectData';
import { BottomAction } from '@/components';
import { history } from 'umi';
import QueryPage from '@/components/QueryPage';
import { withRoutePage } from '@/utils/enhanceUtils';
import { parse, addStirng } from './utils';
import SearchTree from './component/SearchTree';

const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8 }
};
const formTailLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8, offset: 4 }
};
const radioStyle = {
    // display: 'block',
    // height: '30px',
    // lineHeight: '30px'
};
const radioStyleSp = {
    // display: 'block',
    // height: 'auto',
    // lineHeight: '30px'
};

const AddRole = ({ form, dispatch, post, role, location, loading }) => {
    // 获取cookie信息
    const user = localStorage.getItem('user');
    const userInfo = user ? JSON.parse(user) : {};
    const { getFieldDecorator } = form;
    const { department, menuList, roleDetail = {}, defaultDepartment } = role;
    const [companyTreeData, companyTreeLoading] = useTreeSelectData('company');
    const {
        // 角色详情接口现在下发的 menuList dataMenulist 目前是一样的数据，注意提交时dataMenulist前后要拼接空格
        menuList: datamenulist
    } = roleDetail;
    const { companyTree } = post;
    const [radioChoose, setRadioChoose] = useState(true);

    useEffect(() => {
        // 公司树
        Promise.all([
            dispatch({
                type: 'post/fetchCompanyTree',
                payload: {}
            }),
            dispatch({
                type: 'role/fetchMenuList',
                payload: {
                    companyId: userInfo.companyId
                }
            })
        ]).then(() => {
            if (location && location.query.action === 'edit') {
                dispatch({
                    type: 'role/roleDetail',
                    payload: {
                        id: location.query.id // 登录信息中获取
                    },
                    success: roleDetails => {
                        // const { companyId } = roleDetails;
                        if (roleDetails.dataScope === '1') {
                            setRadioChoose(false);
                        }
                        if (roleDetails.dataScope === '3') {
                            // 部门树
                            dispatch({
                                type: 'role/fetchDepartmentList',
                                payload: { companyId: roleDetails.companyId }
                            });
                        }
                    }
                });
            }
        });
        // 清除数据
        return () => {
            dispatch({
                type: 'role/saveRole',
                payload: { department: [], roleDetail: {} }
            });
        };
    }, []);
    // const renderCompanyTreeNodes = companyTrees =>
    //     companyTrees.map(item => {
    //         const title = item.companyName;
    //         if (item.children) {
    //             return (
    //                 <TreeSelect.TreeNode title={title} key={`${item.id}-${item.parentId}`} value={item.id}>
    //                     {renderCompanyTreeNodes(item.children)}
    //                 </TreeSelect.TreeNode>
    //             );
    //         }
    //         return <TreeSelect.TreeNode key={`${item.id}-${item.parentId}`} title={title} value={item.id} />;
    //     });
    // 支持公司和部门数据联动
    const companyConnectLimit = (value, label, extra) => {
        if (extra && extra.triggerNode && extra.triggerNode.props) {
            const parentID = extra.triggerNode.props.eventKey.split('-');
            if (parentID[1] === '0') {
                setRadioChoose(false);
            } else {
                setRadioChoose(true);
            }
            form.setFieldsValue({ dataScope: '' });
            dispatch({
                type: 'role/saveRole',
                payload: { defaultDepartment: [] }
            });
            // 部门树
            dispatch({
                type: 'role/fetchDepartmentList',
                payload: {
                    companyId: extra.triggerNode.props.value
                }
            });
        }
    };
    const renderDepartmentTreeNodes = departmentTrees =>
        departmentTrees.map(item => {
            const title = item.departmentName;
            if (item.children) {
                return (
                    <TreeSelect.TreeNode title={title} key={item.id} value={item.id}>
                        {renderDepartmentTreeNodes(item.children)}
                    </TreeSelect.TreeNode>
                );
            }
            return <TreeSelect.TreeNode key={item.id} title={title} value={item.id} />;
        });
    let companyNameChoose;
    const companyNameChoosed = (id, companyTrees) => {
        const cId = id;
        return companyTrees.forEach(item => {
            if (item.id === cId) {
                companyNameChoose = item.companyName;
            }
            if (item.children) {
                companyNameChoosed(cId, item.children);
            }
        });
    };
    // 提交表单
    const check = () => {
        form.validateFields((err, values) => {
            if (!err) {
                companyNameChoosed(values.companyId, companyTree);
                dispatch({
                    type: 'role/testAddRole',
                    payload: {
                        ...values,
                        menuList: values.menuList && values.menuList ? values.menuList.join(',') : '',

                        dataDepartment: values.dataDepartment ? values.dataDepartment.join(',') : '',
                        dataMenuList: values.menuList && values.menuList ? addStirng(values.menuList.join(',')) : '',

                        companyName: companyNameChoose,
                        createUser: userInfo.userName, // 登录信息
                        id: location && location.query.action === 'edit' ? location.query.id : null
                    }
                });
            }
        });
    };
    const departmentChoose = initCompanyId => {
        // 重新编辑角色 直接切换数据权限 发起部门树申请
        if (location && location.query.action === 'edit' && department.length === 0) {
            // 部门树
            dispatch({
                type: 'role/fetchDepartmentList',
                payload: { companyId: initCompanyId }
            });
        }
        form.validateFields(['dataDepartment'], {
            rules: [
                {
                    required: true,
                    message: '请选择！'
                }
            ]
        });
    };
    const config = [
        {
            field: 'roleName',
            label: '角色名称',
            component: <Input placeholder="请输入角色名称" />,
            props: {
                ...formItemLayout,
                extra: '2--50个字符'
            },
            config: {
                initialValue: roleDetail.roleName ? roleDetail.roleName : '',
                rules: [
                    {
                        required: true,
                        min: 2,
                        max: 50,
                        message: '请输入2~50个字符'
                    }
                ]
            }
        },
        {
            field: 'companyId',
            label: '角色所属',
            component: (
                // <TreeSelect
                //     // treeData={postData}
                //     // treeCheckable
                //     placeholder="请选择角色所属"
                //     allowClear
                //     onChange={companyConnectLimit}
                //     treeDefaultExpandedKeys={
                //         companyTree && companyTree.length > 0 ? [`${companyTree[0].id}-${companyTree[0].parentId}`] : []
                //     }
                //     // style={{ width: 500, marginLeft: 2 }}
                // >
                //     {renderCompanyTreeNodes(companyTree)}
                // </TreeSelect>
                <TreeSelectPro
                    loading={companyTreeLoading}
                    treeDefaultExpandAll
                    showSearch
                    placeholder="请选择角色所属"
                    allowClear
                    treeData={companyTreeData}
                    onChange={companyConnectLimit}
                    treeDefaultExpandedKeys={
                        companyTree && companyTree.length > 0 ? [`${companyTree[0].id}-${companyTree[0].parentId}`] : []
                    }
                />
            ),
            props: {
                ...formItemLayout
            },
            config: {
                initialValue: roleDetail.companyId ? roleDetail.companyId : [],
                rules: [{ required: true, message: '请选择角色所属!' }]
            }
        },
        {
            field: 'dataScope',
            label: '数据权限',
            component: (
                <Radio.Group
                    onChange={() => {
                        dispatch({
                            type: 'role/saveRole',
                            payload: { defaultDepartment: [] }
                        });
                    }}
                >
                    <Radio
                        style={radioStyle}
                        disabled={radioChoose}
                        checked={form.getFieldValue('dataScope') === '1'}
                        value="1"
                    >
                        全集团
                    </Radio>
                    <Radio style={radioStyle} value="2">
                        本公司
                    </Radio>
                    <Radio style={radioStyle} value="4">
                        本部门
                    </Radio>
                    <Radio
                        style={radioStyleSp}
                        value="3"
                        onChange={() => {
                            departmentChoose(roleDetail.companyId);
                        }}
                    >
                        自定义部门，请选择
                    </Radio>
                    {form.getFieldValue('dataScope') === '3'
                        ? getFieldDecorator('dataDepartment', {
                              initialValue:
                                  defaultDepartment.length !== 0
                                      ? defaultDepartment.split(',').filter(s => s && s.trim())
                                      : [],
                              rules: [
                                  {
                                      required: true
                                  }
                              ]
                          })(
                              <TreeSelect
                                  treeCheckable
                                  placeholder="请选择相应部门"
                                  style={{
                                      zIndex: '100',
                                      overflow: '-webkit - paged - x',
                                      display: 'block'
                                  }}
                                  allowClear
                                  //   maxTagCount={1}
                                  //   maxTagPlaceholder={hanldeTreeSelectMore}
                                  showCheckedStrategy={TreeSelect.SHOW_ALL}
                                  //   style={{ width: 300, marginLeft: 5 }}
                              >
                                  {renderDepartmentTreeNodes(department)}
                              </TreeSelect>
                          )
                        : null}
                </Radio.Group>
            ),
            props: {
                ...formItemLayout
            },
            config: {
                initialValue: roleDetail.dataScope ? roleDetail.dataScope : '',
                rules: [
                    {
                        required: true,
                        validator(_, value, callback) {
                            if (value === '3') {
                                if (form.getFieldValue('companyId').length === 0) {
                                    callback('请先选择角色所属!');
                                } else if ((form.getFieldValue('dataDepartment') || []).length === 0) {
                                    callback('请选择自定义部门!');
                                } else {
                                    callback();
                                }
                            } else if (!value) {
                                callback('请选择数据权限');
                            } else {
                                callback();
                            }
                        }
                    }
                ]
            }
        },
        {
            field: 'menuList',
            label: '角色所需功能',
            component: <SearchTree list={parse(menuList)} />,
            props: {
                ...formItemLayout
            },
            config: {
                initialValue: datamenulist ? datamenulist.split(',') : [],
                valuePropName: 'valueProps',
                trigger: 'onCheck',
                rules: [
                    {
                        validator(_, value, callback) {
                            if (value.length <= 0) {
                                callback('请选择角色所需功能！');
                            } else {
                                callback();
                            }
                        }
                    }
                ]
            }
        },
        {
            component: (
                <BottomAction>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        提交
                    </Button>
                    <Button
                        onClick={() => {
                            history.push('/setting/role');
                        }}
                    >
                        取消
                    </Button>
                </BottomAction>
            ),
            props: {
                ...formTailLayout
            }
        }
    ];
    return (
        <Spin spinning={loading}>
            <QueryPage
                form={
                    <Form
                        layout="horizontal"
                        onSubmit={e => {
                            e.preventDefault();
                            check();
                        }}
                        className="addRole"
                    >
                        <QuickForm form={form} config={config} />
                    </Form>
                }
            />
        </Spin>
    );
};

// export default Form.create()(AddRole);
export default withRoutePage(
    connect(({ role, post, loading }) => ({
        role,
        post,
        loading: loading.models.role
    }))(
        Form.create({
            onFieldsChange(props, changedFields) {
                if (changedFields.dataDepartment || changedFields.companyId) {
                    props.form.validateFields(['dataScope', { force: true }]);
                }
            }
        })(AddRole)
    )
);
